package io.gitee.horizon007.webspider.transformer;

import io.gitee.horizon007.webspider.WebSpider;
import io.gitee.horizon007.webspider.annotation.Context;
import io.gitee.horizon007.webspider.metadata.PropertyMetadata;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.List;

public class ElementTransformer implements ValueTransformer {
    @Override
    public Object transform(WebSpider webSpider, Elements elements, Object instance, PropertyMetadata propertyMetadata, Context annotation) throws Throwable {
        if (propertyMetadata.isArray() || propertyMetadata.isList()) {
            if (CollectionUtils.isNotEmpty(propertyMetadata.getGenericParameterList())
                    && propertyMetadata.getGenericParameterList().get(0) == Element.class
            ) {
                return propertyMetadata.isArray() ? elements.toArray() : List.copyOf(elements);
            }
        } else if (propertyMetadata.getClassType() == Element.class) {
            return CollectionUtils.isNotEmpty(elements) ? elements.get(0) : null;
        } else if (propertyMetadata.getClassType() == Elements.class) {
            return elements != null ? elements : new Elements();
        }

        throw new Exception(String.format(
                "When using %s, only data type List<Element>/Element[]/Elements/Element is supported, and the error is: '%s#%s'",
                getClass().getSimpleName(),
                propertyMetadata.getOwner().getType().getName(),
                propertyMetadata.getName()
        ));
    }
}
